using System.Collections.Generic;
using System.Linq;
using UnityEngine;

// 建筑系统主控制器
public class BuildingSystem : MonoBehaviour
{
    public const float CellSize = 1f;  // 每个网格单元的大小

    // 可配置的建筑数据（在Inspector中设置）
    [SerializeField] private BuildingData buildingData1;  // 建筑类型1数据
    [SerializeField] private BuildingData buildingData2;  // 建筑类型2数据
    [SerializeField] private BuildingData buildingData3;  // 建筑类型3数据

    [SerializeField] private BuildingPreview previewPrefab;  // 建筑预览预制体
    [SerializeField] private Building buildingPrefab;       // 建筑实体预制体
    [SerializeField] private BuildingGrid grid;            // 建筑网格系统

    private BuildingPreview preview;  // 当前预览实例

    private void Update()
    {
        Vector3 mousePos = GetMouseWorldPosition();  // 获取鼠标世界坐标

        if (preview != null)
        {
            // 处理建筑预览状态
            HandlePreview(mousePos);
        }
        else
        {
            // 按键1-3创建不同建筑的预览
            if (Input.GetKeyDown(KeyCode.Alpha1))
            {
                preview = CreatePreview(buildingData1, mousePos);
            }
            else if (Input.GetKeyDown(KeyCode.Alpha2))
            {
                preview = CreatePreview(buildingData2, mousePos);
            }
            else if (Input.GetKeyDown(KeyCode.Alpha3))
            {
                preview = CreatePreview(buildingData3, mousePos);
            }
        }
    }

    // 处理建筑预览逻辑
    private void HandlePreview(Vector3 mouseWorldPosition)
    {
        preview.transform.position = mouseWorldPosition;  // 跟随鼠标位置

        // 获取建筑所有单元位置
        List<Vector3> buildPositions = preview.BuildingModel.GetAllBuildingPositions();

        // 检查是否可以建造
        bool canBuild = grid.CanBuild(buildPositions);

        if (canBuild)
        {
            // 对齐到网格中心
            preview.transform.position = GetSnappedCenterPosition(buildPositions);
            preview.ChangeState(BuildingPreview.BuildingPreviewState.POSITIVE);

            // 鼠标左键放置建筑
            if (Input.GetMouseButtonDown(0))
            {
                PlaceBuilding(buildPositions);
            }
        }
        else
        {
            preview.ChangeState(BuildingPreview.BuildingPreviewState.NEGATIVE);
        }

        // R键旋转建筑
        if (Input.GetKeyDown(KeyCode.R))
        {
            preview.Rotate(90);
        }
    }

    // 计算对齐到网格中心的坐标
    private Vector3 GetSnappedCenterPosition(List<Vector3> allBuildingPositions)
    {
        // 获取所有单元的X/Z坐标
        List<int> xs = allBuildingPositions.Select(p => Mathf.FloorToInt(p.x)).ToList();
        List<int> zs = allBuildingPositions.Select(p => Mathf.FloorToInt(p.z)).ToList();

        // 计算中心点并对齐网格
        float centerX = (xs.Min() + xs.Max()) / 2f + CellSize / 2f;
        float centerZ = (zs.Min() + zs.Max()) / 2f + CellSize / 2f;

        return new Vector3(centerX, 0, centerZ);
    }

    // 放置建筑
    private void PlaceBuilding(List<Vector3> buildingPositions)
    {
        // 实例化实际建筑
        Building building = Instantiate(buildingPrefab, preview.transform.position, Quaternion.identity);
        building.Setup(preview.Data, preview.BuildingModel.Rotation);

        // 在网格上注册建筑
        grid.SetBuilding(building, buildingPositions);

        // 清除预览
        Destroy(preview.gameObject);
        preview = null;
    }

    // 获取鼠标在世界空间的位置（Y=0平面）
    private Vector3 GetMouseWorldPosition()
    {
        //Plane.Raycast比传统的Physics.Raycast检测性能好
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Plane groundPlane = new Plane(Vector3.up, Vector3.zero);

        if (groundPlane.Raycast(ray, out float distance))
        {
            return ray.GetPoint(distance);
        }
        return Vector3.zero;
    }

    // 创建建筑预览
    private BuildingPreview CreatePreview(BuildingData data, Vector3 position)
    {
        BuildingPreview buildingPreview = Instantiate(previewPrefab, position, Quaternion.identity);
        buildingPreview.Setup(data);
        return buildingPreview;
    }
}